/*
 * Created by JFormDesigner on Tue Oct 21 21:20:30 CST 2025
 */

package com.yeban.bams.client;

import com.yeban.bams.client.clientsocket.ClientRequest;
import com.yeban.bams.entity.Account;
import com.yeban.bams.exception.AccountNullException;
import com.yeban.bams.exception.NotFoundException;
import com.yeban.bams.server.serversocket.RequestTO;
import com.yeban.bams.server.serversocket.ResponseTO;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * @author yeban
 */
public class LoginPanel extends JPanel {
    private ATMClient atm;

    public LoginPanel(ATMClient atm) {
        this.atm = atm;
        initComponents();
    }

    // 清空表单
    public void clear() {
        userAccountDataField.setText("");
        userPasswordDataField.setText("");
    }

    // 【返回】跳转至主页面
    private void back(java.awt.event.ActionEvent e) {
        CardLayout cardLayout = (CardLayout) atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "mainPanel");
        clear();
    }

    // 【提交】 跳转至业务页面
    private void submit(java.awt.event.ActionEvent e) {
        // 1.收集数据
        String accId = userAccountDataField.getText();
        String password = new String(userPasswordDataField.getPassword());

        // 输入为空校验
        if (accId.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(
                    this,
                    "账号或密码不能为空！",
                    "登录失败",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 账号必须为纯数字
        Long accIdNum;
        try {
            accIdNum = Long.parseLong(accId);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(
                    this,
                    "账号格式错误，请输入纯数字账号！",
                    "输入错误",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 2.构造请求对象
        RequestTO request = new RequestTO(
                "login",
                new Object[] { accIdNum, password },
                new Class[] { Long.class, String.class });

        new SwingWorker<ResponseTO, Void>() {
            @Override
            protected ResponseTO doInBackground() {
                return ClientRequest.send(request);
            }

            @Override
            protected void done() {
                try {
                    ResponseTO response = get();
                    if (response.isSuccess()) {
                        atm.acc = (Account) response.getData();
                        System.out.println("登录成功 - 账户ID: " + (atm.acc != null ? atm.acc.getId() : "null") +
                                ", 姓名: " + (atm.acc != null ? atm.acc.getName() : "null"));
                        if (atm.acc == null || atm.acc.getId() == null) {
                            JOptionPane.showMessageDialog(LoginPanel.this, "登录返回的账户信息不完整！",
                                    "登录失败", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        JOptionPane.showMessageDialog(LoginPanel.this, "欢迎回来~" + atm.acc.getName(),
                                "登录成功",
                                JOptionPane.INFORMATION_MESSAGE);
                        CardLayout layout = (CardLayout) atm.getContentPane().getLayout();
                        layout.show(atm.getContentPane(), "businessPanel");
                        clear();
                        // 先初始化界面，再刷新
                        atm.businessPanel.init();
                        atm.businessPanel.startAutoRefresh();
                    } else {
                        JOptionPane.showMessageDialog(LoginPanel.this, response.getMessage(), "登录失败",
                                JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(LoginPanel.this, "登录失败：" + ex.getMessage(), "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }.execute();
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        userAccountLabel = new JLabel();
        userAccountDataField = new JTextField();
        userPasswordLabel = new JLabel();
        submitButton = new JButton();
        userPasswordDataField = new JPasswordField();
        LoginTitleLabel = new JLabel();
        backButton = new JButton();

        //======== this ========
        setLayout(null);

        //---- userAccountLabel ----
        userAccountLabel.setText("\u7528\u6237\u8d26\u53f7");
        userAccountLabel.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        userAccountLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(userAccountLabel);
        userAccountLabel.setBounds(100, 240, 115, 40);
        add(userAccountDataField);
        userAccountDataField.setBounds(215, 240, 150, 40);

        //---- userPasswordLabel ----
        userPasswordLabel.setText("\u7528\u6237\u5bc6\u7801");
        userPasswordLabel.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        userPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(userPasswordLabel);
        userPasswordLabel.setBounds(100, 300, 115, 40);

        //---- submitButton ----
        submitButton.setText("\u63d0\u4ea4");
        submitButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
        submitButton.addActionListener(e -> submit(e));
        add(submitButton);
        submitButton.setBounds(140, 385, 95, 50);
        add(userPasswordDataField);
        userPasswordDataField.setBounds(215, 300, 150, 40);

        //---- LoginTitleLabel ----
        LoginTitleLabel.setText("\u767b   \u5f55   \u754c   \u9762");
        LoginTitleLabel.setHorizontalAlignment(SwingConstants.CENTER);
        LoginTitleLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 30));
        add(LoginTitleLabel);
        LoginTitleLabel.setBounds(110, 130, 275, 65);

        //---- backButton ----
        backButton.setText("\u8fd4\u56de");
        backButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
        backButton.addActionListener(e -> back(e));
        add(backButton);
        backButton.setBounds(255, 385, 95, 50);

        setPreferredSize(new Dimension(500, 650));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel userAccountLabel;
    private JTextField userAccountDataField;
    private JLabel userPasswordLabel;
    private JButton submitButton;
    private JPasswordField userPasswordDataField;
    private JLabel LoginTitleLabel;
    private JButton backButton;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
